package com.dailywork.basepro.thread.concurrent;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

public class SelfForkJoinPool {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long[] arr = new long[20000];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i;
        }

        ForkJoinPool pool = new ForkJoinPool();
        JoinTask task = new JoinTask(arr, 0, arr.length, 50);
        Future<Long> future = pool.submit(task);
        System.out.println(future.get());
    }
}

class JoinTask extends RecursiveTask<Long> {

    private int start, end;
    private long[] arr;
    private int target;

    JoinTask(long[] arr, int start, int end, int target) {
        this.arr = arr;
        this.start = start;
        this.end = end;
        this.target = target;
    }

    @Override
    protected Long compute() {
        // 如果分配的数组大小达到了指定的大小就执行相加的操作否则就继续拆分
        if (end - start <= target) {
            long result = 0L;
            for (int i = start; i < end; i++) {
                result += arr[i];
            }
            return result;
        } else {
            int mid = start + (end - start) / 2;
            JoinTask j1 = new JoinTask(arr, start, mid, target);
            JoinTask j2 = new JoinTask(arr, mid, end, target);
            // fork()方法时继续查分即会继续调用compute方法
            j1.fork();
            j2.fork();
            return j1.join() + j2.join();
        }
    }
}
